from rest_framework import generics, permissions
from rest_framework.response import Response
from .models import Favorite
from .serializers import FavoriteSerializer, FavoriteCreateSerializer

class FavoriteListView(generics.ListCreateAPIView):
    serializer_class = FavoriteSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Favorite.objects.filter(user=self.request.user)
    
    def get_serializer_class(self):
        if self.request.method == 'POST':
            return FavoriteCreateSerializer
        return super().get_serializer_class()
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class FavoriteDetailView(generics.DestroyAPIView):
    queryset = Favorite.objects.all()
    permission_classes = [permissions.IsAuthenticated]
    lookup_field = 'pk'
    
    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)

class ClearFavoritesView(generics.GenericAPIView):
    permission_classes = [permissions.IsAuthenticated]
    
    def post(self, request):
        deleted, _ = Favorite.objects.filter(user=request.user).delete()
        return Response({
            'message': f'已清除 {deleted} 条收藏记录',
            'count': deleted
        })